package com.devilvan.betrice.bilibili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devilvan.betrice.bilibili.dto.BilibiliReviewDto;
import com.devilvan.betrice.bilibili.po.BilibiliReviewPo;
import com.devilvan.betrice.bilibili.service.BilibiliReviewService;
import com.devilvan.betrice.bilibili.mapper.BilibiliReviewMapper;
import com.devilvan.betrice.bilibili.repository.BilibiliReviewRepository;
import com.devilvan.betrice.util.UEmpty;
import com.devilvan.betrice.util.UCopy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Evad.Wu
 * @Description Bilibili-评论/回复信息表 业务逻辑类
 * @date 2022-12-22
 */
@Service
public class BilibiliReviewServiceImpl extends ServiceImpl<BilibiliReviewMapper, BilibiliReviewPo> implements BilibiliReviewService {
    @Resource(name = "bilibiliReviewRepository")
    private BilibiliReviewRepository bilibiliReviewRepository;

    @Override
    public BilibiliReviewPo saveUpdate(BilibiliReviewDto bilibiliReviewDto) {
        BilibiliReviewPo bilibiliReviewPo = new BilibiliReviewPo();
        UCopy.fullCopy(bilibiliReviewDto, bilibiliReviewPo);
        return bilibiliReviewRepository.saveAndFlush(bilibiliReviewPo);
    }

    @Override
    public List<BilibiliReviewPo> saveUpdateBatch(List<BilibiliReviewDto> list) {
        List<BilibiliReviewPo> bilibiliReviewPoList = UCopy.fullCopyCollections(list, BilibiliReviewPo.class);
        return bilibiliReviewRepository.saveAllAndFlush(bilibiliReviewPoList);
    }

    @Override
    public void distinctSaveReviewByRpid(List<BilibiliReviewDto> bilibiliReviewDtoList) {
        if (UEmpty.isEmpty(bilibiliReviewDtoList)) {
            return;
        }
        List<BilibiliReviewPo> bilibiliReviewPoList = UCopy.fullCopyCollections(bilibiliReviewDtoList, BilibiliReviewPo.class);
        List<Long> rpidList = bilibiliReviewPoList.stream().map(BilibiliReviewPo::getRpid).toList();
        LambdaQueryWrapper<BilibiliReviewPo> queryWrapper = new QueryWrapper<BilibiliReviewPo>().lambda();
        queryWrapper.in(BilibiliReviewPo::getRpid, rpidList);
        queryWrapper.groupBy(BilibiliReviewPo::getRpid);
        List<BilibiliReviewPo> exsistReviewPoList = this.list(queryWrapper);
        List<BilibiliReviewPo> distinctReviePoList = UCopy.checkAssemble(bilibiliReviewPoList, exsistReviewPoList, BilibiliReviewPo::getRpid);
        bilibiliReviewRepository.saveAllAndFlush(distinctReviePoList);
    }
}
